package com.xiaodeng.xdblogspringboot.mapper;

import com.xiaodeng.xdblogspringboot.pojo.Comments;
import com.xiaodeng.xdblogspringboot.pojo.Likes;
import com.xiaodeng.xdblogspringboot.pojo.VO.LikesVO;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface CommentsMapper {
    // ============== 评论相关操作 ==============

    /**
     * 查询评论是否存在
     */
    @Select("SELECT 1 FROM comments WHERE comment_id = #{commentId} LIMIT 1")
    Integer existsComment(@Param("commentId") Long commentId);

    // ============== 文章点赞统计相关操作 ==============

    /**
     * 查询文章点赞统计是否存在
     */
    @Select("SELECT 1 FROM like_statistics WHERE target_id = #{articleId} AND like_type = 1 LIMIT 1")
    Integer existsArticleLike(@Param("articleId") Long articleId);

    /**
     * 更新评论点赞量
     */
    @Update("UPDATE comments SET like_count = like_count + #{delta} WHERE comment_id = #{commentId}")
    void updateCommentLike(@Param("commentId") Long commentId, @Param("delta") int delta);

    /**
     * 新增文章点赞统计（初始点赞数=1）
     */
    @Insert("INSERT INTO like_statistics (target_id, like_type, like_count, update_time) " +
            "VALUES (#{articleId}, 1, 1, NOW())")
    void insertArticleLike(@Param("articleId") Long articleId);

    /**
     * 更新文章点赞统计（点赞数+1）
     */
    @Update("UPDATE like_statistics SET like_count = like_count + #{delta}, update_time = NOW() " +
            "WHERE target_id = #{articleId} AND like_type = 1")
    void updateArticleLike(@Param("articleId") Long articleId, @Param("delta") int delta);

    /**
     * 查询评论当前点赞量
     */
    @Select("SELECT like_count FROM comments WHERE comment_id = #{commentId}")
    int getCommentLikeCount(@Param("commentId") Long commentId);

    /**
     * 查询文章当前点赞量
     */
    @Select("SELECT like_count FROM like_statistics " +
            "WHERE target_id = #{articleId} AND like_type = 1")
    int getArticleLikeCount(@Param("articleId") Long articleId);

    /**
     * 插入点赞记录
     */
    @Insert("INSERT INTO likes (" +
            "user_id, article_id, like_type, target_id, create_time, status" +
            ") VALUES (" +
            "#{userId}, #{articleId}, #{likeType}, #{targetId}, NOW(), #{status}" +
            ")")
    int insertLikes(Likes likes);

    /**
     * 根据用户ID、目标ID和类型查询点赞记录（判断是否已点赞）
     */
    @Select("SELECT id FROM likes " +
            "WHERE user_id = #{userId} AND target_id = #{targetId} AND like_type = #{likeType} AND status = 1")
    Long existsByUserAndTarget(@Param("userId") Long userId,
                               @Param("targetId") Long targetId,
                               @Param("likeType") Short likeType);

    /**
     * 更新点赞状态（取消点赞：status=0 ）
     *
     * @param likeId 喜欢 ID
     * @return int
     */
    @Update("DELETE from likes WHERE id = #{id}")
    int cancelLike(@Param("id") Long likeId);

    /**
     * 插入新评论（使用自增主键）
     */
    @Insert("INSERT INTO comments (" +
            "article_id, user_id, parent_comment_id, content, " +
            "create_time, update_time, like_count, status) " +
            "VALUES (#{articleId}, #{userId}, #{parentCommentId}, #{content}, " +
            "#{createTime}, #{updateTime}, #{likeCount}, #{status})")
    @Options(useGeneratedKeys = true, keyProperty = "commentId", keyColumn = "comment_id")
    void insertComment(Comments comment);

    /**
     * 查询文章下的所有评论（按创建时间升序）
     */
    @Select("SELECT * FROM comments WHERE article_id = #{articleId} AND status = '1' ORDER BY create_time ASC")
    List<Comments> selectByArticleId(@Param("articleId") Long articleId);

    /**
     * 根据ID查询评论
     */
    @Select("SELECT * FROM comments WHERE comment_id = #{commentId}")
    Comments selectById(@Param("commentId") Long commentId);

    /**
     * /**
     * 更新评论状态（单个）
     */
    @Update("UPDATE comments SET status = #{status}, update_time = NOW() " +
            "WHERE comment_id = #{commentId} AND status = 1")
    int updateStatus(@Param("commentId") Long commentId, @Param("status") short status);

    /**
     * 根据父评论ID查询子评论
     */
    @Select("SELECT * FROM comments WHERE parent_comment_id = #{parentId} AND status = 1")
    List<Comments> selectByParentId(@Param("parentId") Long parentId);

    /**
     * 根据目标ID和类型查询有效点赞记录（关联用户表）
     */
    @Select({
            "<script>",
            "SELECT",
            "l.id,",
            "l.user_id AS userId,",
            "l.like_type AS likeType,",
            "l.target_id AS targetId,",
            "l.create_time AS createTime,",
            "u.nickname,",
            "u.user_pic AS userPic",
            "FROM likes l",
            "LEFT JOIN user u ON l.user_id = u.id",
            "WHERE l.status = 1",
            "<if test='targetId != null'> AND l.target_id = #{targetId} </if>",
            "<if test='likeType != null'> AND l.like_type = #{likeType} </if>",
            "</script>"
    })
    List<LikesVO> selectValidLikes(@Param("targetId") Long targetId,
                                   @Param("likeType") Short likeType);

    /**
     * 查询所有评论，支持多条违规词搜索
     *
     * @param sensitiveWords 违规词列表
     * @return 评论列表
     */
    @Select({
            "<script>",
            "SELECT * FROM comments",
            "WHERE status = 1",
            "<if test='sensitiveWords != null and sensitiveWords.size() > 0'>",
            "AND (",
            "<foreach item='word' collection='sensitiveWords' separator='OR'>",
            "content LIKE CONCAT('%', #{word}, '%')",
            "</foreach>",
            ")",
            "</if>",
            "ORDER BY create_time DESC",
            "</script>"
    })
    List<Comments> selectAllComments(@Param("sensitiveWords") List<String> sensitiveWords);

    /**
     * 批量更新评论状态（删除）
     */
    @Update({
            "<script>",
            "UPDATE comments SET status = #{status}, update_time = NOW() ",
            "WHERE comment_id IN ",
            "<foreach item='id' collection='commentIds' open='(' separator=',' close=')'>",
            "#{id}",
            "</foreach>",
            " AND status = 1",
            "</script>"
    })
    int batchUpdateStatus(@Param("commentIds") List<Long> commentIds, @Param("status") short status);
}